using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

namespace Elvex
{
    public class TabWidgetView : MonoBehaviour
    {
        public UnityEvent<int> OnSelect { get; } = new UnityEvent<int>();

        public int CurrentIndex { get; private set; } = 0;

        class Page
        {
            public Button Tab { get; }

            public GameObject Widget { get; }

            public Page(Button tab, GameObject widget)
            {
                Tab = tab;
                Widget = widget;
            }
        }

        List<Page>  m_pages = new List<Page>();

        public void Add(Button tab, GameObject widget)
        {
            m_pages.Add(new Page(tab, widget));
            int pageid = m_pages.Count;
            tab.onClick.AddListener(() => { OnSelect.Invoke(pageid); });
        }

        public void Add(string tabname, string widgetname)
        {
            var tabobj = gameObject.GetComponent<Button>(tabname);
            var widgetobj = gameObject.FindChild(widgetname).gameObject;
            m_pages.Add(new Page(tabobj, widgetobj));
            int pageid = m_pages.Count;
            tabobj.onClick.AddListener(() => { OnSelect.Invoke(pageid); });
        }

        public void Show(int index)
        {
            if (CurrentIndex == index )
            {
                return;
            }

            CurrentIndex = index;
            for (int i = 0; i < m_pages.Count; i++)
            {
                m_pages[i].Widget.SetActive( ( i + 1 )  == index);
            }
        }

        private void Awake()
        {

        }
    }
}
